package com.psychology.service;

import com.psychology.dto.RegisterDTO;
import com.psychology.dto.RetrievePasswordDTO;
import com.psychology.entity.User;
import com.psychology.exception.BusinessException;
import com.psychology.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Random;

@Service
@Slf4j
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Transactional
    public User register(RegisterDTO registerDTO) {
        // 检查手机号是否已注册
        if (userRepository.existsByPhone(registerDTO.getPhone())) {
            throw new BusinessException("该手机号已被注册");
        }

        // 创建新用户
        User user = new User();
        user.setPhone(registerDTO.getPhone());
        // 加密密码
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setName(registerDTO.getName());
        user.setGender(registerDTO.getGender());
        user.setUserType(registerDTO.getUserType());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 保存用户
        try {
            return userRepository.save(user);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            throw new BusinessException("注册失败，请稍后重试");
        }
    }

    @Transactional
    public String retrievePassword(RetrievePasswordDTO dto) {
        // 查找用户
        User user = userRepository.findByPhoneAndName(dto.getPhone(), dto.getName())
                .orElseThrow(() -> new BusinessException("用户不存在或信息不匹配"));

        // 生成新的随机密码
        String newPassword = generateRandomPassword();

        // 加密新密码并保存
        user.setPassword(passwordEncoder.encode(newPassword));
        userRepository.save(user);

        // 返回新密码给用户
        return newPassword;
    }

    // 生成8位随机密码
    private String generateRandomPassword() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < 8; i++) {
            int index = random.nextInt(chars.length());
            sb.append(chars.charAt(index));
        }

        return sb.toString();
    }
}